// vp_cai/pages/index/areas.js
var app = getApp();
var vp = require('../../resource/js/vp.js');
// pages/medical-records/upload.js
Page({
  data: {
    tabs: [
      { type: 'outpatient', name: '门诊病历' },
      { type: 'prescription', name: '门诊处方' },
      { type: 'discharge', name: '出院记录' },
      { type: 'physical', name: '体检报告' },
      { type: 'report', name: '报告单' }
    ],
    typeIndex: 0,
	activeType:'outpatient',
    visitDate: '',
    currentDate: '',
    images: [],
	selectImages:[],
	activeUser:{},
  },

  onLoad(options) {
    // 设置当前日期
    const date = new Date();
    const currentDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    this.setData({
		  activeUser:wx.getStorageSync('activeUser')
    })
    // 如果从列表页传入类型，设置默认类型
    let typeIndex = 0;
    if (options.type) {
		this.setData({
			'activeType':options.type
		})
      typeIndex = this.data.tabs.findIndex(item => item.type === options.type);
      if (typeIndex === -1) typeIndex = 0;
    }
    
    this.setData({
      currentDate,
      typeIndex
    });
  },

  // 选择就诊时间
  onDateChange(e) {
	  console.log(e.detail.value)
    this.setData({
      visitDate: e.detail.value
    });
  },

  // 选择资料类型
  onTypeChange(e) {
    this.setData({
      typeIndex: e.detail.value
    });
  },

  // 选择图片
  chooseImage() {
    wx.chooseImage({
      count: 9 - this.data.images.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
		  
		  this.setData({
		    images: [...this.data.images, ...res.tempFilePaths]
		  });
		this.uploadFiles('file',res.tempFilePaths)
      }
    });
  },
  // 统一上传方法
  uploadFiles(field, tempFilePaths) {
  	  var url = app.util.url('Common/upload');
  	  console.log(tempFilePaths)
    tempFilePaths.forEach((tempFilePath, index) => {
  		
      const uploadTask = wx.uploadFile({
        url: url,
        filePath: tempFilePath,
        name: 'file',
        success: res => {
          const data = JSON.parse(res.data)
		  console.log('image:',data)
		  
		  this.setData({
			selectImages: [...this.data.selectImages, data.data.path]
		  });
		  
        },
        fail: () => {
          wx.showToast({ title: '上传失败', icon: 'none' })
        }
      })
    })
  },
  // 删除图片
  removeImage(e) {
    const index = e.currentTarget.dataset.index;
    const images = [...this.data.images];
    images.splice(index, 1);
    this.setData({ images });
  },

  // 提交表单
  async submitForm(e) {
	  const that = this
    const formData = e.detail.value;
    const { visitDate, hospital,title } = formData;
    const recordType = this.data.tabs[this.data.typeIndex].type;
    
    if (!visitDate) {
      wx.showToast({ title: '请选择就诊时间', icon: 'none' });
      return;
    }
    if (!title) {
      wx.showToast({ title: '请输入就诊备注', icon: 'none' });
      return;
    }
    if (!hospital) {
      wx.showToast({ title: '请输入医院名称', icon: 'none' });
      return;
    }
    
    if (this.data.images.length === 0) {
      wx.showToast({ title: '请至少上传一张图片', icon: 'none' });
      return;
    }
    
    // 显示加载中
    wx.showLoading({ title: '上传中...', mask: true });
	console.log(this.data.images)
	console.log(this.data.selectImages)
	console.log('++++++++++++++++++++++++++++')
	// 构造提交数据
	const submitData = {
		title: title,
		family_id:this.data.activeUser.id,
		hospital: hospital,
		visitDate:visitDate,
		type:this.data.activeType,
		image: JSON.stringify(this.data.selectImages)
	}
	// 模拟提交
	await app.util.request({
			  url: 'Medicalmanage/updateSaveImage',
			  data: submitData,
			  success(res) {
				  wx.hideLoading()
				  wx.showModal({
					  title:'提交成功',
					  content: res.data.msg,
					  confirmText: '确定',
					  showCancel: false,
					  success:function(){
						  wx.navigateTo({
						    url: '/vp_pz/pages/familydoctor/medicalrecords?tab='+that.data.activeType
						  });					 
					  }
				  });
			  }
	})
  }
});